package com.kx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kx.dao.QueryDao;
import com.kx.entity.Province;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class QueryProvinceListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String json = "{}";
        //访问dao，查询所有省份信息，list集合
        QueryDao dao = new QueryDao();
        List<Province> provinces = dao.queryProvinceList();
        System.out.println(provinces);
        //把list转为json格式的数据，输出给ajax请求
        if (provinces != null) {
            //调用jackson的工具库，实现List--json
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(provinces);
        }
        //输出json数据，响应ajax请求，返回数据
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.println(json);
        pw.flush();
        pw.close();
    }
}
